package com.dragon.common.core.crypto.digest;

import com.dragon.common.utils.ByteUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * SHA-1摘要
 *
 * @author dragon
 * @version 1.0
 * @date 2024/8/1 9:59
 */
public class SHA1 {

    private static final Logger log = LoggerFactory.getLogger(SHA1.class);

    /**
     * SHA-1摘要
     *
     * @param data 数据
     * @return SHA-1哈希值
     */
    public String digestHex(String data) {
        try {
            /* Java SHA-1 */
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            messageDigest.update(data.getBytes(StandardCharsets.UTF_8));
            // 计算哈希值并转换为16进制字符串
            byte[] digest = messageDigest.digest();

            return ByteUtils.byteToHexString(digest);
        } catch (Exception e) {
            log.error("SHA-1摘要异常 {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }


    /**
     * SHA-1摘要
     *
     * @param data 数据
     * @return SHA-1哈希值
     */
    public String digestHex(byte[] data) {
        try {
            /* Java SHA-1 */
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            messageDigest.update(data);
            // 计算哈希值并转换为16进制字符串
            byte[] digest = messageDigest.digest();

            return ByteUtils.byteToHexString(digest);
        } catch (Exception e) {
            log.error("SHA-1摘要异常 {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    /**
     * SHA-1摘要
     *
     * @param data 数据
     * @return SHA-1哈希值
     */
    public String digestHex(InputStream data) {
        try {
            /* Java SHA-1 */
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            messageDigest.update(data.readAllBytes());
            // 计算哈希值并转换为16进制字符串
            byte[] digest = messageDigest.digest();

            return ByteUtils.byteToHexString(digest);
        } catch (Exception e) {
            log.error("SHA-1摘要异常 {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

}
